package com.xiaoma.myaudience.biz.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.SendPhonecodeTask;
import com.xiaoma.myaudience.biz.task.UpdateUserInfoTask;
import com.xiaoma.myaudience.biz.task.UserInfoDetailTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;

public class EditUserInfoActivity extends BaseActivity {
	private final static String TAG = "UpdateUserInfoTask";
	private EditText inputtext ;
	private UpdateUserInfoTask mUpdateUserInfoTask;
	private String type;
	private String content;
	private ProgressDialog mUserInfoDetailDialog;
	
	private LinearLayout mUserinfoSimplelayout;
	private LinearLayout mUserinfoAgePickerlayout;
	private LinearLayout mUserinfoGenderlayout;
	private LinearLayout mUserinfoPasswdlayout;
	private LinearLayout mUserinfoCellPhonelayout;
	private DatePicker datePicker;
	private RadioGroup genderRadiogroup;
	private ProgressDialog mSendPhoneNumProgressDialog;
	private EditText mInputPhonecode;
	private SendPhonecodeTask mSendCodeTask;
	private Button mBtnSendPhoneCode;
	private EditText mInputPhoneNumber;
	private String authcode;
	private String sphonenummer;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_edit_layout);
		//get the editText
		initLayout();
		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		String code = intent.getStringExtra("code");
		String value = intent.getStringExtra("value");
		type = code;
		//修改密码
		if(code.equals("1")){
			mUserinfoPasswdlayout.setVisibility(View.VISIBLE);
			
		}else if(code.equals("8")){//年龄选择
			mUserinfoAgePickerlayout.setVisibility(View.VISIBLE);
			int year = new Date().getYear();
			if(!value.equals("")){
					year = Integer.valueOf(value);
			}
			//適配2.3和4.x
			int currentapiVersion=android.os.Build.VERSION.SDK_INT;
			if(currentapiVersion<11){
				((ViewGroup) datePicker.getChildAt(0)).getChildAt(1).setVisibility(View.GONE);
				((ViewGroup) datePicker.getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
			}else{
				((LinearLayout) ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
				((LinearLayout) ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0)).getChildAt(1).setVisibility(View.GONE);
			}
			datePicker.init(year, 2, 1,null);
		}else if(code.equals("7")){//性别选择
			mUserinfoGenderlayout.setVisibility(View.VISIBLE);
			int gendername = value.equals("男")?1:2;
			if(!value.equals("未知")){
			 RadioButton radioButton = (RadioButton) genderRadiogroup.getChildAt(gendername-1);  
			 radioButton.setChecked(true);
			}
			
		}else if(code.equals("10")){//手机号修改
			mUserinfoCellPhonelayout.setVisibility(View.VISIBLE);
			mBtnSendPhoneCode.setOnClickListener(new OnClickListener() {
				

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					sphonenummer = mInputPhoneNumber.getText().toString().trim();
					if((sphonenummer.length())!=11){
						Tips("手机号码位数不对");
						return;
					}else{
						
					}
					startSendCodeTask(sphonenummer);
				}
			});
		}else{//其他编辑框
			mUserinfoSimplelayout.setVisibility(View.VISIBLE);
			inputtext =(EditText)findViewById(R.id.edit_edituserinfo_value);
			inputtext.setText(value);
			inputtext.setFocusable(true);
			inputtext.setFocusableInTouchMode(true);
			inputtext.requestFocus();
		}
		setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitle("编辑"+name);
        setNetEaseTitleGravity(Gravity.CENTER);
        setNetEaseTitleBarExtra(R.layout.video_detail_extra_layout);
        findViewById(R.id.show_comments_back_original).setVisibility(View.VISIBLE);
        
        findViewById(R.id.show_comments_back_original).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startUpdateTask();
			}
		});
        
        findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(EditUserInfoActivity.this, LoginActivity.class);
				startActivity(intent);
				cancelUpdateTask();
				EditUserInfoActivity.this.finish();
			}
		});
	}
	
	
	//密码验证
	private boolean ivalidpasswd(){
		
		//密码
		EditText editPwd = (EditText)findViewById(R.id.edit_changepwd_newpassword);
		String password = String.format("%s",editPwd.getText());
		//验证
		if("".equals(password)){
			Tips(getResources().getString(R.string.str_password_is_null),Toast.LENGTH_SHORT);
			return false;
		}
		//重复密码
		EditText editRePwd = (EditText)findViewById(R.id.edit_changepwd_renewssword);
		String repassword = String.format("%s",editRePwd.getText());
		//验证
		if("".equals(repassword)){
			Tips(getResources().getString(R.string.str_password_is_null),Toast.LENGTH_SHORT);
			return false;
		}else if(!repassword.equals(password)){
			Tips("两次输入密码不同",Toast.LENGTH_SHORT);
			return false;
		}
		content=password;
		return true;
	}
	
	
	/**启动任务保存任务*/
	private void startUpdateTask() {
		cancelUpdateTask();
		
		mUpdateUserInfoTask = new UpdateUserInfoTask(this,
				DataAsyncTask.TASK_ACTIVITY_UPDATEUSERINFO, this);
		//取用户数据
		if(type.equals("1")){
			if(!ivalidpasswd()){
				return;
			}
		}else if(type.equals("8")){
			int year = datePicker.getYear();
            int m = datePicker.getMonth();
            int d = datePicker.getDayOfMonth();
            content=year+","+d+","+m;
		}else if(type.equals("7")){//性别选择
			for (int i = 0; i < genderRadiogroup.getChildCount(); i++) {  
                RadioButton radioButton = (RadioButton) genderRadiogroup.getChildAt(i);  
                if(radioButton.isChecked()) {  
                    content = i+1+"";
                    break;  
                }  
            }  
		}else if(type.equals("10")){//手机号修改
			authcode = mInputPhonecode.getText().toString().trim();
			if(authcode.length()!=6){
				Tips("请输入正确的验证码");
				return;
			}
			this.content = sphonenummer;
		}else{//其他编辑框
			content = inputtext.getText().toString();
			if(content==null || content.equals("")){
				Tips("请输入修改值");
				return;
			}
		}
		
		
		Map<String,String> cookie = new HashMap<String,String>();
			cookie.put("type",this.type);
			cookie.put("content",content);
			if(type.equals("10")){
				cookie.put("authcode",authcode);
			}
			cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(EditUserInfoActivity.this,Constant.LOGIN_COOKIE1,""));
			cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(EditUserInfoActivity.this,Constant.LOGIN_COOKIE2,""));
			mUpdateUserInfoTask.execute(cookie);
	}
	
	/**关闭保存任务*/
	private void cancelUpdateTask() {
		if (mUpdateUserInfoTask != null) {
			mUpdateUserInfoTask.cancel(true, true);
		}
		mUpdateUserInfoTask = null;
	}
	//启动发送手机验证码任务
	public void startSendCodeTask(String phonenummer){
		cancelSendCodeTask();
		mSendCodeTask = new SendPhonecodeTask(this,
				DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM, this);
		mSendCodeTask.execute(phonenummer);
	}
	//取消
	public void cancelSendCodeTask(){
		if (mSendCodeTask != null) {
			mSendCodeTask.cancel(true, true);
		}
		mSendCodeTask = null;
	}
	
	@Override
	public void onPreExecute(int what) {
		// TODO Auto-generated method stub
		super.onPreExecute(what);
		if(what==DataAsyncTask.TASK_ACTIVITY_UPDATEUSERINFO){
			if(null == mUserInfoDetailDialog){
				mUserInfoDetailDialog = new ProgressDialog(this);
				mUserInfoDetailDialog.setMessage("正在保存。。。");
				mUserInfoDetailDialog.setCancelable(true);
				mUserInfoDetailDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						cancelUpdateTask();
					}
				});
			}
			mUserInfoDetailDialog.show();
		}
		
		if(what==DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM){
			if(null == mSendPhoneNumProgressDialog){
				mSendPhoneNumProgressDialog = new ProgressDialog(this);
				mSendPhoneNumProgressDialog.setMessage("正在发送...");
				mSendPhoneNumProgressDialog.setCancelable(true);
			}
			mSendPhoneNumProgressDialog.show();
		}
	}
	
	@Override
	public void onPostExecute(int what, Object o) {
		super.onPostExecute(what, o);
		if(what==DataAsyncTask.TASK_ACTIVITY_UPDATEUSERINFO){
				if(null != mUserInfoDetailDialog)
					mUserInfoDetailDialog.dismiss();
				
			//取出用户详细信息
			String  code = (String)o;
			String tips = "";
			if(code!=null){
				int intcode =Integer.valueOf(code);
				
				switch (intcode) {
				case 0:
					tips="保存成功";
					Intent intent =new Intent(EditUserInfoActivity.this,UserInfoDetailActivity.class);
					startActivity(intent);
					break;
				case -1:
					tips="必须传递op的值，且为edit";
					break;
				case -2:
					tips="必须选择修改的类型";
					break;
				case -3:
					tips="内容格式有误";
					break;
				case -100:
					tips="请先登录，才能操作";
					break;
				default:
					break;
				}
			}else{
				tips="保存失败，请重试";
			}
			Tips(tips);
			}
		if(what==DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM){
			if(null == mSendPhoneNumProgressDialog){
				mSendPhoneNumProgressDialog.dismiss();
				}
			if(null != mSendPhoneNumProgressDialog)
				mSendPhoneNumProgressDialog.dismiss();
			//取出
			String  code = (String)o;
			String tips = "";
			if(code!=null){
				if(code.equals("0")){
					tips="发送成功";
					//验证码输入框置为可用
					mInputPhonecode.setEnabled(true);
				}else if(code.equals("-1")){
					tips="手机号不正确";
				}else if(code.equals("2")){	
					tips = "发送失败，请稍后再试";
				}

			}
			Tips(tips);
			
			}
		}

	private void initLayout(){
		mUserinfoSimplelayout =(LinearLayout)findViewById(R.id.edituserinfo_layout_simpleinput);
		mUserinfoAgePickerlayout =(LinearLayout)findViewById(R.id.edituserinfo_layout_simple_agepicker);
		mUserinfoGenderlayout=(LinearLayout)findViewById(R.id.edituserinfo_layout_gender);
		mUserinfoPasswdlayout=(LinearLayout)findViewById(R.id.edituserinfo_changepwd);
		mUserinfoCellPhonelayout =(LinearLayout)findViewById(R.id.layout_changePhoneNummer);
		datePicker =(DatePicker)findViewById(R.id.edituserinfo_picker_datepicher);
		genderRadiogroup=(RadioGroup)findViewById(R.id.edituserinfo_raidiogroup_gender);
		mInputPhonecode =(EditText)findViewById(R.id.edit_code);
		mBtnSendPhoneCode =(Button)findViewById(R.id.btn_getphonecode);
		mInputPhoneNumber =(EditText)findViewById(R.id.edit_phonenum);
	}
}
